package me.stone.stanimeclient.base

import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import me.stone.stanimeclient.R
import me.stone.stanimeclient.SACApplication
import me.stone.stanimeclient.core.model.DarkThemeMode
import me.stone.stanimeclient.ui.DarkThemeModeImpl
import me.stone.stanimeclient.ui.updateDarkThemeMode
import me.stone.stanimeclient.util.autoCleared


abstract class AbsViewBindingActivity<V: ViewBinding>: AppCompatActivity() {

    protected var binding by autoCleared<V>()

    protected var navHostFragment: NavHostFragment? = null

    protected var navController: NavController? = null

    protected val sacApplication: SACApplication
        get() = application as SACApplication

    protected val darkThemeMode: DarkThemeModeImpl
        get() = sacApplication.darkThemeMode

    private var currentDarkThemeMode: DarkThemeMode? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        currentDarkThemeMode = darkThemeMode.currentDarkThemeMode
            .also { updateDarkThemeMode(it) }
        super.onCreate(savedInstanceState)
        lifecycleScope.launch {
            darkThemeMode.darkThemeModeFlow.collectLatest {
                if (currentDarkThemeMode == it) return@collectLatest
                currentDarkThemeMode = it
                updateDarkThemeMode(it)
            }
        }

        binding = buildViewBinding()
        enableEdgeToEdge()
        setContentView(binding.root)
        ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets ->
            getCustomInsets(insets.getInsets(WindowInsetsCompat.Type.systemBars()))?.let {
                v.setPadding(it.left, it.top, it.right,
                    if (hasBottomNavigationView()) 0 else it.bottom
                )
            } ?: let { v.setPadding(0, 0, 0, 0) }
            insets
        }
        findNavigationHost()
    }

    open fun findNavigationHost() {
        navHostFragment = supportFragmentManager
            .findFragmentById(R.id.fragments) as? NavHostFragment
        navController = navHostFragment?.navController
    }

    abstract fun buildViewBinding(): V

    open fun hasBottomNavigationView(): Boolean = false

    open fun getCustomInsets(insets: Insets): Insets? {
        return insets
    }

}